package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeadNewsException;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Integer userId, String keyword) {
        //查询当前用户的搜索记录中是否存在当前关键词
        Query query = new Query(Criteria.where("userId").is(userId).and("keyword").is(keyword));

        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        if (apUserSearch != null) {
            //更新最新时间
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        } else {
            // 判断当前用户搜索记录总量是否大于等于10
            Query keywordQuery = new Query(Criteria.where("userId").is(userId));
            //按照创建时间倒序
            keywordQuery.with(Sort.by(Sort.Order.desc("createdTime")));
            List<ApUserSearch> searchList = mongoTemplate.find(keywordQuery, ApUserSearch.class);

            ApUserSearch newApUserSearch = new ApUserSearch();
            newApUserSearch.setUserId(userId);
            newApUserSearch.setKeyword(keyword);
            newApUserSearch.setCreatedTime(new Date());

            int size = searchList.size();
            if (CollectionUtils.isNotEmpty(searchList)|| size <10) {
                //新增记录
                mongoTemplate.save(newApUserSearch);
            }else {
                ApUserSearch lastSearch = searchList.get(size - 1);
                Query replaceQuery = new Query(Criteria.where("_id").is(lastSearch.getId()));

                mongoTemplate.findAndReplace(replaceQuery,newApUserSearch);
                // Update update = new Update();
                // update.set("keyword",keyword);
                // update.set("createdTime",new Date());
                // mongoTemplate.updateFirst(replaceQuery,update,ApUserSearch.class);
            }
        }
    }

    @Override
    public ResponseResult load() {
        ApUser user = (ApUser) ThreadLocalUtils.get();
        if(user!=null){
            Query query = Query.query(Criteria.where("userId").is(user.getId()));
            //按照时间倒序
            query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
            query.limit(10);
            List<ApUserSearch> searchList = mongoTemplate.find(query, ApUserSearch.class);
            return ResponseResult.okResult(searchList);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public void del(String id) {
        //判断是否登录后操作
        ApUser user = (ApUser)ThreadLocalUtils.get();
        if(user==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //删除mongo记录
        Query query = Query.query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,ApUserSearch.class);
    }
}
